<template>
    <ContainerView>
        <div class="row">
            <div class="col-9">
                <div class="card">
                    <div class="card-body">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th scope="col">ID</th>
                                    <th scope="col">Project Name</th>
                                    <th scope="col">Overtime</th>
                                    <th scope="col">Hours</th>
                                    <th scope="col" v-if="$store.state.is_admin">Operation</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="user in users" :key="user.id">
                                    <th scope="row">{{ user.id }}</th>
                                    <td>{{ user.project }}</td>
                                    <td>{{ user.overtime ? 'Yes' : 'No' }}</td>
                                    <td>{{ user.hours }}</td>
                                    <td v-if="$store.state.is_admin">
                                        <button type="button" class="btn btn-danger" @click="() => delete_a_user(user.id)">
                                            Delete
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-3">
                <div class="card h-100">
                    <div class="card-body d-flex flex-column">
                        <h5 class="card-title">项目累计工时</h5>
                        <div class="chart-container flex-grow-1">
                            <canvas ref="chartCanvas"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </ContainerView>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import ContainerView from './ContainerView.vue';
import Chart from 'chart.js/auto';

export default {
    name: 'ComEmployeeListView',
    components: {
        ContainerView
    },
    setup() {
        const users = ref([
            {
                "id": "001",
                "project": "Road Project A",
                "overtime": true,
                "hours": 3.5,
                "created_at": "2024-04-10 10:30"
            },
            {
                "id": "002",
                "project": "Bridge Maintenance B",
                "overtime": false,
                "hours": 2,
                "created_at": "2024-04-09 13:00"
            },
            {
                "id": "003",
                "project": "Pipeline Fix C",
                "overtime": true,
                "hours": 4.5,
                "created_at": "2024-04-08 08:00"
            },
            {
                "id": "004",
                "project": "Bridge Maintenance B",
                "overtime": true,
                "hours": 3,
                "created_at": "2024-04-07 16:45"
            },
            {
                "id": "005",
                "project": "Tunnel Cleaning D",
                "overtime": false,
                "hours": 8.1,
                "created_at": "2024-04-03 11:43"
            }
        ]);

        const chartCanvas = ref();
        const chartInstance = ref(null);
        const resizeObserver = ref(null);
        const isUpdatingChart = ref(false);

        const calculateProjectHours = () => {
            const projectHours = {};
            users.value.forEach(user => {
                if (!projectHours[user.project]) {
                    projectHours[user.project] = 0;
                }
                projectHours[user.project] += user.hours;
            });
            return {
                labels: Object.keys(projectHours),
                data: Object.values(projectHours),
            };
        };

        const destroyChart = () => {
            if (chartInstance.value) {
                try {
                    chartInstance.value.destroy();
                } catch (e) {
                    console.warn('Chart destroy error:', e);
                }
                chartInstance.value = null;
            }
            if (resizeObserver.value) {
                resizeObserver.value.disconnect();
                resizeObserver.value = null;
            }
        };

        const initChart = async () => {
            if (!chartCanvas.value || isUpdatingChart.value) return;
            
            isUpdatingChart.value = true;
            destroyChart();
            
            await nextTick();
            
            try {
                const { labels, data } = calculateProjectHours();
                const ctx = chartCanvas.value.getContext('2d');
                
                const container = chartCanvas.value.parentElement;
                if (container) {
                    const width = container.clientWidth;
                    const height = container.clientHeight;
                    chartCanvas.value.width = width;
                    chartCanvas.value.height = height;
                }

                chartInstance.value = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels,
                        datasets: [{
                            label: '累计工时（小时）',
                            data,
                            backgroundColor: [
                                'rgba(255, 99, 132, 0.7)',
                                'rgba(54, 162, 235, 0.7)',
                                'rgba(255, 206, 86, 0.7)',
                                'rgba(75, 192, 192, 0.7)',
                                'rgba(153, 102, 255, 0.7)',
                            ],
                            borderColor: [
                                'rgba(255, 99, 132, 1)',
                                'rgba(54, 162, 235, 1)',
                                'rgba(255, 206, 86, 1)',
                                'rgba(75, 192, 192, 1)',
                                'rgba(153, 102, 255, 1)',
                            ],
                            borderWidth: 1,
                        }],
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        resizeDelay: 100,
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '工时（小时）',
                                },
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: '项目名称',
                                },
                            },
                        },
                        plugins: {
                            legend: {
                                position: 'top',
                            },
                            tooltip: {
                                mode: 'index',
                                intersect: false,
                            },
                        },
                        animation: {
                            duration: 500
                        },
                    },
                });

                if (container) {
                    resizeObserver.value = new ResizeObserver(() => {
                        if (chartInstance.value) {
                            chartInstance.value.resize();
                        }
                    });
                    resizeObserver.value.observe(container);
                }
            } catch (error) {
                console.error('Chart initialization error:', error);
            } finally {
                isUpdatingChart.value = false;
            }
        };

        const safeUpdateChart = async () => {
            if (users.value.length === 0) {
                destroyChart();
                return;
            }
            
            if (!isUpdatingChart.value) {
                await initChart();
            }
        };

        onMounted(() => {
            initChart();
        });

        onBeforeUnmount(() => {
            destroyChart();
        });

        watch(users, () => {
            safeUpdateChart();
        }, { deep: true });

        const delete_a_user = async (user_id) => {
            users.value = users.value.filter(user => user.id !== user_id);
        };

        return {
            users,
            chartCanvas,
            delete_a_user
        };
    }
};
</script>

<style scoped>
.row {
    height: calc(50vh - 70px);
}
.card {
    height: 100%;
}
.card-body {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 1rem;
}
.chart-container {
    position: relative;
    width: 100%;
    height: 100%;
    min-height: 300px;
}
.table {
    width: 100%;
    margin-bottom: 0;
}
.table th, .table td {
    vertical-align: middle;
    padding: 0.5rem;
}
.btn-danger {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
}
</style>